package com.day6.server.handler;

import com.day6.protocol.request.MessageRequestPacket;
import com.day6.protocol.response.MessageResponsePacket;
import com.day6.session.Session;
import com.day6.util.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author leonard
 * @Description SimpleChannelInboundHandler:
 * 实现泛型判断和对象传递，减少if else代码来判断是什么类型的通信对象,专注与指令的逻辑
 * @date 2021-05-28 11:07
 */
public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageRequestPacket messageRequestPacket) throws Exception {

        //获取消息发送方的session信息
        Session session = SessionUtil.getSession(channelHandlerContext.channel());

        //读取发送方的通信数据并构造返回给客户端的通信数据
        MessageResponsePacket responsePacket = new MessageResponsePacket();
        responsePacket.setFromUserId(session.getUserId());
        responsePacket.setFromUserName(session.getUserName());
        responsePacket.setMessage(messageRequestPacket.getMessage());

        //通过session拿去发送端的channel
        Channel toUserChannel = SessionUtil.getChannel(messageRequestPacket.getToUserId());

        //开始发送
        if(toUserChannel!=null&&SessionUtil.hasLogin(toUserChannel)){
            toUserChannel.writeAndFlush(responsePacket);
        }else{
            System.err.println("===>"+session.getUserId()+"权限不足");
        }
    }
}
